/**
 * 动态注册路由
 */
import router from './index'
import { get } from '../utils/request'
import api from '../api'
import store from '../store'
import routerLayout from 'lib-comp/layout/routerView.vue'
import { CustomRouteRaw } from 'lib-plugins/vueRouter/type'
const configJson = require('../../package.json')
const addRoutes = (routes: CustomRouteRaw[], parentName = '') => {
  routes.forEach((item: CustomRouteRaw) => {
    if (item.path && item.component && item.appInfo.baseUrl === configJson.appBaseUrl) {
      const componentString = item.component.replace(/^\/+/, ''), // 过滤字符串前面所有 '/' 字符
        componentPath = componentString.replace(/\.\w+$/, ''); // 过滤掉后缀名，为了让 import 加入 .vue ，不然会有警告提示...
      const route = {
        path: item.path,
        redirect: item.redirect,
        name: item.name,
        component: item.component === 'routerLayout' ? routerLayout : () => import(`@/views/${componentPath}.vue`),
        meta: item.meta,
        children: []
      }
      parentName ? router.addRoute(parentName + '', {
        ...route
      }) : router.addRoute({
        ...route
      });
      if (item.children && item.children.length) {
        addRoutes(item.children, item.name);
      }
    }
  })
};


const getTopRouter = (menuList: CustomRouteRaw[]) => {
  let topRouter = '' // 登录后跳转的第一个路由
  const filterMenuList = store.state.common.menuList.filter(item => item.appInfo.baseUrl === configJson.appBaseUrl)
  const router = filterMenuList[0]
  if (router.children && router.children.length > 0) {
    topRouter = router.children[0].path
  } else {
    topRouter = router.path
  }
  return topRouter
}

export const registerRoutes = () => {
  return new Promise((resolve, reject) => {
    // 获取当前登录用户的权限
    if (!store.state.common.menuList || store.state.common.isRefreshPage) {
      store.commit('setCommonStore', {
        isRefreshPage: false
      })
      get(api.user.userPermission).then((res: any) => {
        addRoutes(res.menuList);
        console.log(3333)
        resolve(getTopRouter(res.menuList))
      })
    } else {
      addRoutes(store.state.common.menuList);
      console.log(router.getRoutes())
      resolve(getTopRouter(store.state.common.menuList))
    }
    // // 添加404页面
    // router.addRoute({
    //   path: "/",
    //   redirect: "/404",
    //   name: "NotFound",
    // })
  })
}